using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

namespace WbsEditor
{
    public partial class BatchChildEditControl : UserControl
    {
        public BatchChildEditControl()
        {
            InitializeComponent();
        }

        private WbsNode _node;
        [Browsable(false)]
        public WbsNode WbsNode
        {
            get { return _node; }
            set { _node = value; }
        }

        private WorkBreakdownStructure _wbs;
        [Browsable(false)]
        public WorkBreakdownStructure Wbs
        {
            get { return _wbs; }
            set { _wbs = value; }
        }

        [Browsable(false)]
        public IWbsNodeFactory NodeFactory
        {
            get;
            set;
        }


        public event EventHandler SaveRequested;
        public event EventHandler CancelRequested;

        public void DisplayControl()
        {
            _childNodeGrid.Rows.Clear();
            foreach (WbsNode child in WbsNode.ChildNodes)
            {
                int rowNr = _childNodeGrid.Rows.Add();
                DataGridViewRow row = _childNodeGrid.Rows[rowNr];
                row.Cells["Title"].Value = child.Title;
                row.Cells["Title"].Tag = child;
                bool readOnly = child.IsPublished;
                row.Cells["AssignedTo"].Value = child.AssignedTo;
                MarkReadOnly(row.Cells["AssignedTo"], readOnly);
                row.Cells["RemainingWork"].Value = Wbs.ToDisplayTimeUnits(child.RemainingWorkInDays).ToString();
                MarkReadOnly(row.Cells["RemainingWork"], readOnly);
                row.Cells["CompletedWork"].Value = Wbs.ToDisplayTimeUnits(child.CompletedWorkInDays).ToString();
                MarkReadOnly(row.Cells["CompletedWork"], readOnly);
            }

            Visible = true;
        }

        public void WriteBackChanges()
        {
            List<WbsNode> childNodeList = new List<WbsNode>();
            foreach (DataGridViewRow row in _childNodeGrid.Rows)
            {
                string title = GetCellValue(row, "Title");
                if (string.IsNullOrEmpty(title))
                    continue;
                // May be null for new rows
                WbsNode node = (WbsNode)row.Cells["Title"].Tag;
                if (null == node)
                {
                    node = NodeFactory.CreateWbsNode();
                    node.Parent = WbsNode;
                    node.LayoutMode = WbsEditor.WbsNode.NodeLayout.Vertical;
                }
                node.Title = title;
                if (!node.IsPublished)
                {
                    string assignedTo = GetCellValue(row, "AssignedTo");
                    node.AssignedTo = assignedTo;
                    string remainingWork = GetCellValue(row, "RemainingWork");
                    string completedWork = GetCellValue(row, "CompletedWork");
                    float remainingWorkInDays = 0f;
                    float completedWorkInDays = 0f;
                    if (float.TryParse(remainingWork, out remainingWorkInDays))
                        node.RemainingWorkInDays = Wbs.FromDisplayTimeUnits(remainingWorkInDays);
                    if (float.TryParse(completedWork, out completedWorkInDays))
                        node.CompletedWorkInDays = Wbs.FromDisplayTimeUnits(completedWorkInDays);
                }
                childNodeList.Add(node);
            }

            WbsNode.ChildNodes.Clear();
            WbsNode.ChildNodes.AddRange(childNodeList);
        }

        private string GetCellValue(DataGridViewRow row, string col)
        {
            if (null == row.Cells[col])
                return "";
            if (null == row.Cells[col].Value)
                return "";
            return row.Cells[col].Value.ToString();
        }

        private void MarkReadOnly(DataGridViewCell cell, bool readOnly)
        {
            if (readOnly)
            {
                cell.ReadOnly = true;
                cell.Style.BackColor = Color.LightGray;
            }
        }

        private void _okButton_Click(object sender, EventArgs e)
        {
            Visible = false;
            SaveRequested(this, new EventArgs());
        }

        private void _cancelButton_Click(object sender, EventArgs e)
        {
            Visible = false;
            CancelRequested(this, new EventArgs());
        }

        private void _childNodeGrid_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            DataGridViewRow row = e.Row;
            if (null != row.Cells["Title"].Tag)
            {
                WbsNode node = (WbsNode)row.Cells["Title"].Tag;
                if (node.IsPublished)
                {
                    DialogResult res = MessageBox.Show("The row you are about to delete refers to a published Work Item.\n\n" +
                        "Do you really want to proceed?", "Confirm", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                    if (DialogResult.Cancel == res)
                        e.Cancel = true;
                }
                if (node.HasChildNodes)
                {
                    MessageBox.Show("The row you request to delete refers to a node with child nodes.\n\n" +
                        "It cannot be deleted.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    e.Cancel = true;
                }
            }
        }
    }
}
